<template>
	<view class="user-question">
		<div class="fiexd">
			<Header :centerTitleWhiteMany="pageName"></Header>
		</div>

		<view class="content-wrapper">
			<scroll-view id="scroll-view" :style="{height: scrollHeight, backgroundColor: '#f7f8f9'}" scroll-y
				:scroll-with-animation="true" :scroll-into-view="`#msg-${msgItem}`">
				<view class="msg-wrapper" id="msg-view">
					<view v-for="(item, index) in msgList" :key="index" :id="`msg-${index}`">
						<view class="item self" v-if="item.userContent != ''">
							<view class="content right" style="color: #ffffff;">
								{{item.userContent}}
							</view>
						</view>
						<view class="item Ai" v-if="item.botContent != ''">
							<image class="avatar" src="@/static/index/AI.png"></image>
							<view class="content left" :id="'boxmsg-' + index">
								{{ item.displayContent }}
							</view>
						</view>
					</view>
				</view>
			</scroll-view>

			<view class="input-wrapper" :style="inputWrapperStyle">
				<textarea class="input" v-model="queryParams.content" placeholder="输入你的问题或需求"
					placeholderStyle="color: #606266" auto-height :fixed="true" :show-confirm-bar="false"
					:adjust-position="false" @focus="handleFocus()" />
				<view style="width: 18%;">
					<u-button shape="circle" color="#181818" @click="handleSend()">发送</u-button>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import questionData from '@/utils/question.js'; // 导入JSON数据
	export default {
		data() {
			return {
				pageName: "AI聊天",
				scrollTop: 0,
				keyboardHeight: 0, // 键盘高度
				bottomHeight: 0, // 发送框高度
				// 查询条件
				queryParams: {
					content: null
				},
				// 文本框样式
				inputStyle: {
					padding: '10px',
					margin: '0px 10px 0px 0px',
					border: '1.5px solid #181818 !important',
					borderRadius: '15px',
				},
				inputWrapperStyle: '',
				// 消息列表
				msgList: [],
				msgItem: 0
			};
		},
		created() {
			this.init()
		},
		computed: {
			inputHeight() {
				return this.pxToRpx(this.keyboardHeight)
			},
			windowHeight() {
				return this.pxToRpx(uni.getSystemInfoSync().windowHeight) - this.pxToRpx(this.keyboardHeight)
			},
			scrollHeight() {
				return (this.windowHeight + this.inputHeight - 180) + 'rpx'
			},
		},
		methods: {
			init() {
				this.msgList.splice(0, this.msgList.length)
				let params = {
					userContent: '',
					botContent: '你好！有什么我能帮助你的吗？',
					displayContent: '', // 初始化显示内容为空
					typing: true // 标记为正在打字
				};

				this.msgList.push(params)
				this.queryParams.content = null;
				this.msgItem = this.msgList.length - 1;

				this.startTyping(params, params.botContent, this.msgList.length - 1);
			},
			fetchQuestions(query) {
				const matchedQuestions = questionData.filter(question => question.title.includes(query));
				return matchedQuestions
			},
			async handleSend() {
				let userContent = this.queryParams.content

				if (userContent === null || userContent === '') {
					return uni.$u.toast("发送的内容不能为空！")
				}
				
				const bot = await this.fetchQuestions(userContent)
				console.log(bot)
				
				let params = {
					userContent: userContent,
					botContent: bot[0].answer,
					displayContent: '', // 初始化显示内容为空
					typing: true // 标记为正在打字
				};

				this.msgList.push(params);
				this.queryParams.content = null;
				this.msgItem = this.msgList.length - 1;

				this.startTyping(params, bot[0].answer, this.msgList.length - 1);
			},
			handleFocus() {
				uni.onKeyboardHeightChange(res => {
					this.keyboardHeight = res.height
					this.inputWrapperStyle = (res.height > 0) ? `bottom: ${res.height}px;` : '';
				});
			},
			// px转换成rpx
			pxToRpx(px) {
				let deviceWidth = uni.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			// rpx转px
			rpxToPx(rpxValue) {
				const systemInfo = uni.getSystemInfoSync();
				const windowWidth = systemInfo.windowWidth;
				const rpxBase = 750; // 微信小程序中rpx相对于750rpx宽度的屏幕的换算关系

				// 计算1rpx等于多少px
				const pxPerRpx = windowWidth / rpxBase;

				// 将传入的rpx值转换为px
				return Math.round(rpxValue * pxPerRpx);
			},
			startTyping(item, content, index) {
				let charIndex = 0;
				let interval = setInterval(() => {
					if (charIndex < content.length) {
						item.displayContent = content.substring(0, charIndex + 1);
						charIndex++;
					} else {
						clearInterval(interval);
						item.typing = false; // 打字完成
					}
				}, 100); // 每隔100毫秒添加一个字符
			}
		}
	}
</script>

<style lang="scss">
	.user-question {

		.content-wrapper {
			position: relative;
		}

		.msg-wrapper {
			padding: 20px 0px 150px;

			.self {
				justify-content: flex-end;
			}

			.item {
				display: flex;
				padding: 0px 15px 15px;

				.right {
					background-color: #4facfe;
				}

				.left {
					overflow: hidden;
					background-color: #ffffff;
				}

				//聊天消息的三角形
				.right::after {
					position: absolute;
					display: inline-block;
					content: '';
					width: 0;
					height: 0;
					left: 100%;
					top: 10px;
					border: 12rpx solid transparent;
					border-left: 12rpx solid #4facfe;
				}

				.left::after {
					position: absolute;
					display: inline-block;
					content: '';
					width: 0;
					height: 0;
					top: 10px;
					right: 100%;
					border: 12rpx solid transparent;
					border-right: 12rpx solid #FFFFFF;
				}

				.content {
					position: relative;
					max-width: 486rpx;
					border-radius: 8rpx;
					word-wrap: break-word;
					padding: 10px;
					margin: 0 10px;
					border-radius: 5px;
					font-size: 16px;
				}

				.avatar {
					@include flex($align: center);
					width: 78rpx;
					height: 78rpx;
					background: #ffffff;
					border-radius: 50rpx;
					overflow: hidden;

					image {
						align-self: center;
					}

				}
			}
		}

		.input-wrapper {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			@include flex($align: center);
			padding: 10px 15px;
			border-top: 1px solid #f0f0f0;
			background-color: #ffffff;

			.input {
				padding: 10px;
				margin: 0px 10px 0px 0px;
				border: 1.5px solid #181818 !important;
				border-radius: 15px;
			}
		}
	}
</style>